﻿using System;
using System.Data;
using System.Configuration;
using System.Web.SessionState;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;
using System.Net.Mail;
using System.Web;
using QualityRpt.Service;

namespace QualityRpt.Utils
{
    /// <summary>
    /// AppUtils 的摘要说明
    /// </summary>
    public class AppUtils
    {
        static log4net.ILog logger = log4net.LogManager.GetLogger("AppUtils");
        public AppUtils()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        public static readonly string st_validate_code = "st.vc";//验证码
        public static readonly string st_session_key = "st.session_key";//用户信息
        public static readonly string st_message_key = "st.message_key";//提示信息
        public static readonly string st_current_file = "st.current_file";//当前唯一的文件
        public static readonly string st_last_login = "st.last_login";//上次登录时间
        public static string last_error_url = string.Empty;
        /// <summary>
        /// 获得网站名称
        /// </summary>
        /// <returns></returns>
        public static string GetWebName()
        {
            return ConfigurationManager.AppSettings["WebName"];
        }
        /// <summary>
        /// 是否登录
        /// </summary>
        public static bool isLogin(HttpSessionState session)
        {
            if (session[AppUtils.st_session_key] != null)
            {
                return true;
            }
            return false;
        }
        public static DataRow GetUser(HttpSessionState session)
        {
            DataTable rtTable = session[AppUtils.st_session_key] as DataTable;
            if (rtTable != null && rtTable.Rows.Count > 0)
            {
                return rtTable.Rows[0];
            }
            else
            {
                return null;
            }
        }
        public static string GetUserName(HttpSessionState session)
        {
            string rt = string.Empty;
            DataRow log_row = GetUser(session);
            if (log_row != null)
            {
                rt = log_row["USER_NAME"].ToString();
            }
            return rt;
        }
        public static long GetUserId(HttpSessionState session)
        {
            DataRow logURow = GetUser(session);
            if (logURow != null)
            {
                return Convert.ToInt64(logURow["ID"]);
            }
            else
            {
                return 0;
            }
        }
        public static void SetUser(HttpSessionState session, DataTable loggedUserTable)
        {
            session[AppUtils.st_session_key] = loggedUserTable;
        }
        public static DateTime GetLastLogin(HttpSessionState session)
        {
            if (session[st_last_login] != null)
            {
                return (DateTime)session[st_last_login];
            }
            return DateTime.Now;
        }
        /// <summary>
        /// 设置会话级的文件
        /// </summary>
        public static void SetCurrentOneFile(HttpSessionState session, string isrc)
        {
            session[st_current_file] = isrc;
        }
        /// <summary>
        /// 获得会话级的唯一文件
        /// </summary>
        public static string GetCurrentOneFile(HttpSessionState session)
        {
            object onefile = session[st_current_file];
            string rtfile = string.Empty;
            if (onefile != null)
            {
                rtfile = onefile.ToString();
            }
            return rtfile;
        }
        /// <summary>
        /// 删除会话级的唯一文件
        /// </summary>
        /// <param name="session"></param>
        public static void DelCurrentOneFile(HttpSessionState session)
        {
            session[st_current_file] = null;
        }
        /// <summary>
        /// 清除所有业务端缓存
        /// </summary>
        public static void ClearAllCache()
        {
            IDictionaryEnumerator de = HttpRuntime.Cache.GetEnumerator();
            ArrayList keyList = new ArrayList();
            while (de.MoveNext())
            {
                string key = de.Key.ToString();
                keyList.Add(key);
            }
            for (int i = 0; i < keyList.Count; i++)
            {
                HttpRuntime.Cache.Remove(keyList[i].ToString());
            }
        }
        /// <summary>
        /// 根据url获得Html
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetHtml(string url)
        {
            string pageHtml = string.Empty;
            WebClient MyWebClient = new WebClient();
            try
            {
                MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
                MyWebClient.Encoding = UTF8Encoding.UTF8;
                pageHtml = MyWebClient.DownloadString(url);
            }
            catch (WebException webEx)
            {
                Console.WriteLine(webEx.Message.ToString());
            }
            finally
            {
                MyWebClient.Dispose();
            }
            return pageHtml;
        }
        /// <summary>
        /// 根据url获得Html
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetHtml(string url, string encodestr)
        {
            string pageHtml = string.Empty;
            WebClient MyWebClient = new WebClient();
            try
            {
                MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
                MyWebClient.Encoding = Encoding.GetEncoding(encodestr);

                pageHtml = MyWebClient.DownloadString(url);
            }
            catch (WebException webEx)
            {
                Console.WriteLine(webEx.Message.ToString());
            }
            finally
            {
                MyWebClient.Dispose();
            }
            return pageHtml;
        }
        /// <summary>
        /// 获得图片的存储路径及名字
        /// </summary>
        /// <param name="special">指定的特殊名字</param>
        /// <param name="suffix">图片后缀</param>
        /// <returns></returns>
        public static string GetImagePath(string special, string suffix)
        {
            return GetPath("images", special, suffix);
        }
        public static string GetTempPath(string speical, string suffix)
        {
            return GetPath("temp", speical, suffix);
        }
        public static string GetPath(string objType, string special, string suffix)
        {
            DateTime now = DateTime.Now;
            string path = "/uploads/" + objType + "/" + now.ToString("yyyyMM");
            if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/").ToString() + path))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/").ToString() + path);
            }
            return path + "/" + special + "_" + now.ToString("ddHHmmss") + "." + suffix;
        }
        /// <summary>
        /// 获得客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetClientIp()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        /// <summary>
        /// 发送电子邮件
        /// </summary>
        /// <param name="SendEmail"></param>
        /// <param name="Title"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
		public static void SendMail(string fromName, string SendEmail, string Title, string Content,string attach_file, bool fssl)
        {
            MailMessage mailObj = new MailMessage();

            mailObj.From = new MailAddress(ConfigurationManager.AppSettings["SendUserName"], fromName);
            //添加收件人
            string[] emailArr = SendEmail.Split(new char[] { ';', ',', '，', '；' });
            foreach (string email in emailArr)
            {
                if (email != null && email.Trim() != string.Empty)
                {
                    mailObj.To.Add(email);
                }
            }
            mailObj.Subject = Title;
            mailObj.Body = Content;
            mailObj.IsBodyHtml = true;
			if (attach_file.Trim () != string.Empty) {
				mailObj.Attachments.Add (new Attachment (attach_file));
			}
            SmtpClient smtp = new SmtpClient();
            smtp.Host = ConfigurationManager.AppSettings["MailServer"];
            smtp.Port = int.Parse(ConfigurationManager.AppSettings["SendPort"]);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (fssl)
            {
                smtp.EnableSsl = true;
            }
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["SendUserName"], ConfigurationManager.AppSettings["SendPassword"]);
            smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
            object userState = mailObj;
            smtp.SendAsync(mailObj, userState);
        }

        static void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MailMessage mm = e.UserState as MailMessage;
            logger.Info("发送email" + mm.Subject + "成功.个数" + mm.To.Count + " Email地址 " + mm.To.ToString());
        }

        /// <summary>
        /// 获得AppSetting键值对
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppKey(string _key)
        {
            foreach (string key in ConfigurationManager.AppSettings.AllKeys)
            {
                if (key == _key)
                {
                    return ConfigurationManager.AppSettings[_key];
                }
            }
            return string.Empty;
        }
        //
        public static string GetPlazaName(object organ_id)
        {
            string rt = string.Empty;
            if(organ_id!=null&& organ_id!=DBNull.Value)
            {
                DataRow rtRow = NetWorkPlazaService.GetByORGAN_ID(Convert.ToInt32(organ_id));
                if (rtRow != null)
                {
                    rt = rtRow["ORGAN_NAME"].ToString();
                }
            }
            return rt;
        }
    }
}
